<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #box {
        height: 500px;
        width: 800px;
        border: 2px solid #000;
      }
    </style>
  </head>

  <body>
    <div id="box"></div>
    <div>
      <button id="start">开始</button>
      <button id="stop">结束</button>
    </div>

    <script>
      let boxEle = document.getElementById('box')
      let startEle = document.getElementById('start')
      let stopEle = document.getElementById('stop')

      let timer

      // 随机生成一个16进制颜色
      function randomHexColor() {
        let arr = ['A', 'B', 'c', 'D', 'E', 'F', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        let color = '#'
        for (let i = 1; i <= 6; i++) {
          let newArr = arr[parseInt(Math.random() * arr.length)]
          color += newArr
        }
        return color
      }

      startEle.addEventListener('click', function () {
        if (timer) {
          return
        }
        timer = setInterval(function () {
          let randomColor = randomHexColor()
          boxEle.style.backgroundColor = randomColor
        }, 100)
      })
      stopEle.addEventListener('click', function () {
        clearInterval(timer)
        timer = undefined
      })
    </script>
  </body>
</html>
